// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import Vuex from 'vuex'
import App from './App'
import router from './router'
import VueResource from 'vue-resource'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'

import global_ from './components/Global'
Vue.prototype.GLOBAL = global_
Vue.config.productionTip = false
Vue.use(VueResource)
Vue.use(Vuex)
Vue.use(ElementUI)

/* eslint-disable no-new */
new Vue({
    el: '#app',
    router,
    components: { App },
    template: '<App/>'
})


// 全局导航钩子
router.beforeEach((to, from, next) => {
    // 判断该路由是否需要登录权限
    if (to.meta.requireAuth) {
        // 通过vuex state获取当前的token是否存在
        if (sessionStorage.getItem("user") != null) {
            next();
        } else {
            next({
                path: '/login',
                query: { redirect: to.fullPath } // 将跳转的路由path作为参数，登录成功后跳转到该路由
            })
        }
    } else {
        next();
    }
});

//http 全局拦截器
Vue.http.interceptors.push((request, next) => {
    //将请求转换成post
    request.method = 'POST';
    // 跨域携带cookie
    request.credentials = true;
    //在响应之后传给then之前对response进行修改和逻辑判断。
    //对于token时候已过期的判断，就添加在此处，页面中任何一次http请求都会先调用此处方法
    next((response) => {
        //  console.log("调用http获取到的响应值")
        //  console.log(response);
        if (response.code == '0000') {
            return response;
        } else if (response.status == '301') {
            router.push({ path: '/login', query: { redirect: response.url } })
        }
    })

})